import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:study/list/chapterone.dart';


class Homepage extends StatefulWidget {
  @override
  _HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(vsync: this);
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  List<HomeItem> widgets = [];
  List<HomeGridItem> Gridwidgets = [];

  @override
  Widget build(BuildContext context) {
    return new DefaultTabController(
        length: 2,
        child: new Scaffold(
          body: new CustomScrollView(
              slivers: <Widget>[
                new SliverAppBar( //头部为一个SliverAppBar，折叠部分的内容都放在了flexibleSpace中。
                  pinned: true,
                  floating: true,//那么AppBar会在你做出下拉手势时就立即展开
                  expandedHeight: 300.0,
                  // 这个高度必须比flexibleSpace高度大

                  bottom: PreferredSize(
                      child: new Container(
                          width: 500,
                          height: 46,
                          color: Colors.white,
                          padding: EdgeInsets.only(left: 15.0, right: 15.0,top: 5.0, bottom: 5.0),
                          child: new Material(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(20.0),
                            elevation: 5.0,
                            child: new Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                new Icon(Icons.search),
                                new Text('点击搜索',
                                    textAlign: TextAlign.center,
                                    style: new TextStyle(
                                        color: Colors.grey,
                                        fontSize: 16
                                    )
                                ),
                              ],
                            ),

                          )
                      ),
                      //只要你的控件实现了 preferredSize，就可以放到 AppBar 的 bottom 中使用。比如下图搜索栏，这是TabView下的页面又实用了AppBar。
                      preferredSize: new Size(double.infinity, 46.0)
                  ),

                  flexibleSpace: new Container(
                    child: new Column(
                      children: <Widget>[
                        new Expanded(
                          child: new Container(
                            child: Image.network(
                              "http://pics.sc.chinaz.com/files/pic/pic9/201804/zzpic11492.jpg",
                              fit: BoxFit.cover,
                            ),
                            width: double.infinity,
                          ),
                        )
                      ],
                    ),
                  ),
                ),
//                SliverPersistentHeader(
////                pinned: true,
////                floating: true,
//                  delegate: _SliverAppBarDelegate(
//                      minHeight: 50.0,
//                      maxHeight: 50.0,
//                      child: new Container(
//                          width: 500,
//                          margin: EdgeInsets.only(
//                              left: 15.0, right: 15.0, top: 10.0),
//                          child: new Material(
//                            color: Colors.white,
//                            borderRadius: BorderRadius.circular(20.0),
//                            elevation: 5.0,
//                            child: new Center(
//                              child: new Text('点击搜索',
//                                  textAlign: TextAlign.center,
//                                  style: new TextStyle(
//                                      color: Colors.grey,
//                                      fontSize: 18
//                                  )
//                              ),
//                            ),
//                          )
//                      )
//                  ),
//                ),

                new SliverList(
                  delegate: SliverChildBuilderDelegate((BuildContext context,
                      int index) {
                    return getItem(index);
                  },
                    childCount: widgets.length,
                  ),
                ),


                new SliverToBoxAdapter(
                  child: new Container(
                      margin: EdgeInsets.only(top: 15.0,),
                      child: new Row(
                        children: <Widget>[
                          new Expanded(child: new Container(
                            child: new Text("学习使我快乐",
                              style: new TextStyle(
                                  color: Colors.black45
                              ),
                            ),
                            padding: EdgeInsets.only(left: 20.0, top: 20.0),
                            margin: EdgeInsets.only(left: 15.0, right: 5.0),
                            height: 150,
                            decoration: new BoxDecoration(
                                borderRadius: BorderRadius.all(
                                    const Radius.circular(5.0)),
                                image: DecorationImage(
                                    image: NetworkImage("http://pics.sc.chinaz.com/files/pic/pic9/201609/fpic7419.jpg"),
                                    fit: BoxFit.cover)
                            ),
                          )
                          ),
                         Expanded(
                            child: new Column(
                            children: <Widget>[
                              new Container(
                                child: new Text("学成雕塑",
                                  style: new TextStyle(
                                      color: Colors.white
                                  ),
                                ),
                                height: 70,
                                padding: EdgeInsets.only(left: 10.0, top: 10.0),
                                margin: EdgeInsets.only(
                                  left: 5.0,
                                  right: 15.0,
                                  bottom: 5.0,),
                                width: double.infinity,
                                decoration: new BoxDecoration(
                                    borderRadius: BorderRadius.all(
                                        const Radius.circular(5.0)),
                                    image: DecorationImage(
                                        image: NetworkImage("http://pics.sc.chinaz.com/files/pic/pic9/201702/bpic445.jpg"),
                                        fit: BoxFit.cover)
                                ),

                              ),
                              new Container(
                                padding: EdgeInsets.only(left: 10.0, top: 10.0),
                                margin: EdgeInsets.only(
                                    left: 5.0,
                                    right: 15,
                                    top: 5.0),
                                child: new Text("学到自闭",
                                  style: new TextStyle(
                                      color: Colors.white
                                  ),),
                                height: 70,
                                width: double.infinity,
                                decoration: new BoxDecoration(
                                    borderRadius: BorderRadius.all(
                                        const Radius.circular(5.0)),
                                    image: DecorationImage(
                                        image: NetworkImage("http://pics.sc.chinaz.com/files/pic/pic9/201706/bpic2006.jpg"),
                                        fit: BoxFit.cover)
                                ),
                              )
                            ],
                          ))
                        ],
                      )
                  ),
                ),

                SliverList(
                  delegate: SliverChildBuilderDelegate((BuildContext context,
                      int index) {
                    return getItem(index);
                  },
                    childCount: widgets.length,
                  ),
                ),

                SliverPersistentHeader(
//                pinned: true,
//                floating: true,
                  delegate: _SliverAppBarDelegate(
                      minHeight: 60.0,
                      maxHeight: 180.0,
                      child: new Card(
                        margin: EdgeInsets.all(10),
                        elevation: 5.0,
                        child: new Container(
                            padding: EdgeInsets.only(bottom: 20.0),
                            alignment: Alignment.bottomCenter,
                            decoration: new BoxDecoration(
                                image: DecorationImage(image: NetworkImage(
                                    "http://pics.sc.chinaz.com/files/pic/pic9/201804/zzpic11538.jpg"),
                                  fit: BoxFit.cover,
                                )
                            ),
                            child: new Text("一个人看书 一个人学习",
                              style: new TextStyle(
                                color: Colors.white,
                                fontSize: 26,
                              ),
                            )
                        ),
                      )
                  ),
                ),

                SliverGrid(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2, //一行多少个
                  ),
                  delegate: SliverChildBuilderDelegate((BuildContext context, int index) {

                    return Card(
                      color: Colors.deepOrangeAccent,
                      margin: EdgeInsets.all(5),
                      child:
                      Container(
                        margin: EdgeInsets.all(1),
                        child: ListTile(
                          title: Text(chapterone[index]["title"]),
                          subtitle: Text(chapterone[index]["description"],overflow: TextOverflow.ellipsis,),
                          selected: true,
                          onTap: () {
                            showDialog(
                                context: context,
                                builder: (context) => AlertDialog(
                                  title: Image.network(chapterone[index]["url"]),
                                  content: Text(chapterone[index]["description"]),
                                  actions: <Widget>[
                                    new FlatButton(
                                      child: new Text("确定"),
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                      },
                                    ),
                                  ],
                                ));
                          },

                        ),
                        decoration: new BoxDecoration(
                          image: DecorationImage(
                            image: NetworkImage(
                              chapterone[index]["url"],
                            ),
                            fit: BoxFit.cover,
                          )
                        ),

                      ),
                      );
                    },
                    childCount: chapterone.length,
                  ),

                ),


              ]
          ),
        )
    );
  }


  Widget getItem(int i) {
    return new HomeItem(
      title: widgets[i].title,
      position: widgets[i].position,
      content: widgets[i].content,
      time: widgets[i].time,
      coverUrl: widgets[i].coverUrl,
      callBack: (postition, item) {
        showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: Text("postion$postition"),
            )
        );
      },
    );
  }

  Widget getGridItem(int i) {
    return new HomeGridItem(
      title: Gridwidgets[i].title,
      position: Gridwidgets[i].position,
      content: Gridwidgets[i].content,
      time: Gridwidgets[i].time,
      coverUrl: Gridwidgets[i].coverUrl,
      callBack: (postition, item) {
        showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: Text("postion$postition"),
            )
        );
      },
    );
  }
}

class HomeItem extends StatelessWidget {


  HomeItem({
    this.title,
    this.position,
    this.time,
    this.content,
    this.callBack,
    this.coverUrl
}) : super(key:new ObjectKey(position));

  String title;
  int position;
  String content;
  String coverUrl;
  String time;
  CallBack callBack;
  @override
  Widget build(BuildContext context) {
    print('bookId:$position');
    Widget titleSection = new Container(
        padding: const EdgeInsets.fromLTRB(10.0, 8.0, 10.0, 8.0),
        child:
        new Card(
            elevation: 5.0,
            child:new Container(
              padding: const EdgeInsets.all(10.0),
              child: new Column(
                children: <Widget>[
                  new Container(
                    width: double.infinity,
                    height: 100.0,
                    margin: EdgeInsets.fromLTRB(0, 0, 0, 10.0),
                    child: new Image.network("http://pics.sc.chinaz.com/files/pic/pic9/201911/zzpic21033.jpg",
                      fit: BoxFit.cover,
                    ),
                  ),
                  new Text(
                    title,
                    style: new TextStyle(
                        fontSize: 18,
                        color: Color(0xFF333333)
                    ),
                  ),
                ],
              ),
            )
        )
    );
    return new GestureDetector(
      child: titleSection,
      onTap: () {
        //callBack(position , this);
        showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: Text("小可爱"),
            )
        );
      },
    );
  }

}



class HomeGridItem extends StatelessWidget {
  HomeGridItem({this.title,
    this.position,
    this.content,
    this.time,
    this.coverUrl,
    this.callBack,})
      : super(key: new ObjectKey(position)); //ObjectKey唯一的标识位
  String title;
  int position;
  String content;
  String coverUrl;
  String time;
  CallBack callBack;

  @override
  Widget build(BuildContext context) {
    print('bookId:$position');
    Widget titleSection = new Container(
        padding: const EdgeInsets.fromLTRB(10.0, 8.0, 10.0, 8.0),
        child:
        new Card(
            elevation: 5.0,
            child:new Container(
              padding: const EdgeInsets.all(10.0),
              child: new Column(
                children: <Widget>[
                  new Container(
                    width: double.infinity,
                    height: 100.0,
                    margin: EdgeInsets.fromLTRB(0, 0, 0, 10.0),
                    child: new Image.network(coverUrl,
                      fit: BoxFit.cover,
                    ),
                  ),
                  new Text(
                    title,
                    style: new TextStyle(
                        fontSize: 18,
                        color: Color(0xFF333333)
                    ),
                  ),
                ],
              ),
            )
        )
    );
    return new GestureDetector(
      child: titleSection,
      onTap: () {
        callBack(position, this);
      },
    );
  }
}

typedef void CallBack(
  int position,
    HomeGridItem item,
    );



class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    @required this.child,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => max(maxHeight, minHeight);

  @override
  Widget build(BuildContext context, double shrinkOffset,
      bool overlapsContent) {
    return child;
  }


  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}